/**
 * Project Name:account_server
 * File Name:HttpClientUtil.java
 * Package Name:com.tenpay.c3acct.busi.util
 * Date:2019年1月22日上午9:30:51
 * Copyright (c) 2019, andy.cai All Rights Reserved.
 */

package com.example.wechat.util;

//import com.appleframework.rop.utils.RopUtils;
//import com.taobao.diamond.utils.JSONUtils;
//import com.tianyuan.appauth.busi.exception.BusiErrorCode;
//import com.tianyuan.appauth.busi.exception.BusiException;
//import org.apache.commons.lang.StringUtil;
import com.example.wechat.exception.BusiErrorCode;
import com.example.wechat.exception.BusiException;
import com.taobao.diamond.utils.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName:HttpClientUtil <br/>
 * Function: 发送http请求工具类. <br/>
 * Date: 2019年1月22日 上午9:30:51 <br/>
 *
 * @author p_qiangzuo
 * @since JDK 1.8
 */
public class HttpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String doGet(String url, Map<String, String> param) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (Map.Entry<String, String> entry : param.entrySet()) {
                    builder.addParameter(entry.getKey(), entry.getValue());
                }
            }
            URI uri = builder.build();
            logger.info("sendGet=> {}",uri);
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            RequestConfig config = RequestConfig.custom().setConnectTimeout(20000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpGet.setConfig(config);

            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                logger.info("result=> {}",resultString);
            }
        } catch (Exception e) {
            logger.error("GET请求发送异常", e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                logger.error("GET请求发生IO异常", e);
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null);
    }

    public static String postByForm(String url, Map<String, String> param) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> entry : param.entrySet()) {
                    paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
                httpPost.setEntity(entity);
            }
            logger.info("sendPost=> {}",httpPost);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            logger.info("result=> {}",resultString);
        } catch (Exception e) {
            logger.error("POST请求发生异常", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("POST请求发生IO异常", e);
                }
            }
        }
        return resultString;
    }

//    // form表单提交的post请求
//    public static String postByForm(String url, String param) {
//        Map<String, String> paramMap = StringUtility.kvStrToMap(param);
//        return postByForm(url, paramMap);
//    }

    public static String postByJson(String url, Map<String, Object> param) {
        try {
            String requestStr = JSONUtils.serializeObject(param);
            return postByJson(url, requestStr);
        } catch (Exception e) {
            logger.error(String.format("调用远程接口失败 url:%s param:%s", url, param), e);
            throw new BusiException(BusiErrorCode.ERR_INVOKE_HTTP_INTEFACE.value(), "调用远程接口失败", e);
        }
    }

    public static String postByJson(String url, String requestBodyStr) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        logger.info(String.format("request url:%s", url));
        logger.info(String.format("request body:%s", requestBodyStr));
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (StringUtils.isNotBlank(requestBodyStr)) {
                StringEntity requestBody = new StringEntity(requestBodyStr, ContentType.APPLICATION_JSON);
                httpPost.setEntity(requestBody);
            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            logger.info(String.format("response body:%s", resultString));
        } catch (Exception e) {
            logger.error(String.format("调用远程接口失败 url:%s param:%s", url, requestBodyStr), e);
            throw new BusiException(BusiErrorCode.ERR_INVOKE_HTTP_INTEFACE.value(), "调用远程接口失败", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("POST请求发生IO异常", e);
                }
            }
        }
        return resultString;
    }

    public static String uploadFile(String url, String fileName, byte[] bytes) throws Exception {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpPut httpput = new HttpPut(url);
            ByteArrayEntity reqEntity = new ByteArrayEntity(bytes);
            httpput.setEntity(reqEntity);
            logger.info("executing request " + httpput.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpput);
            try {
                return response.getStatusLine().getStatusCode() + "";
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    }

    public static void testGet() {
        String url = "http://localhost:8080/router";
        Map<String, String> param = new HashMap<String, String>();
        param.put("appkey", "txzx");
        param.put("method", "tx.c3acct.busi.getopenstatus");
        param.put("v", "1.0");
        param.put("format", "json");
        param.put("attach", "123");
        param.put("acct_type", "1");
        param.put("acct_no", "oaB5o5AL1zEFWKIBRTK0gjhdyKbQ");
        param.put("client_ip", "127.0.0.1");
        param.put("sign", "A883B0C229872C072C67FC5ADCE042E8");
        String response = doGet(url, param);
        System.out.println(response);

    }

    // 获取rop请求参数的签名
//    public static String getRopMd5Sign(String needSignParams) {
//        String signSecret = "hmw64w1inqejd9iuboeodljys803f810";
//        Map<String, String> map = StringUtility.kvStrToMap(needSignParams);
//        map.remove("sign");
//        System.out.println(map.toString());
//        return RopUtils.sign(map, signSecret);
//    }

}
